package com.coisshi.base.framework.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.coisshi.base.framework.config.properties.AliyunOssProperties;
import com.coisshi.base.framework.config.properties.CloudStorageProperties;
import com.coisshi.base.framework.config.properties.TencentCosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * OSS配置类
 * 
 * @author coisshi
 * @date 2025/04/28
 */
@Slf4j
@Configuration
public class OssConfig {

    private OSS ossClient;
    private COSClient cosClient;

    @Bean
    public OSS ossClient(CloudStorageProperties cloudStorageProperties) {
        AliyunOssProperties properties = cloudStorageProperties.getAliyun();
        ossClient = new OSSClientBuilder()
                .build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        log.info("初始化阿里云OSS客户端, endpoint: {}, bucket: {}", properties.getEndpoint(), properties.getBucketName());
        return ossClient;
    }

    @Bean
    public COSClient cosClient(CloudStorageProperties cloudStorageProperties) {
        TencentCosProperties properties = cloudStorageProperties.getTencent();
        COSCredentials cred = new BasicCOSCredentials(properties.getSecretId(), properties.getSecretKey());
        Region region = new Region(properties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        cosClient = new COSClient(cred, clientConfig);
        log.info("初始化腾讯云COS客户端, region: {}, bucket: {}", properties.getRegion(), properties.getBucket());
        return cosClient;
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
            log.info("关闭阿里云OSS客户端");
        }
        if (cosClient != null) {
            cosClient.shutdown();
            log.info("关闭腾讯云COS客户端");
        }
    }
}

